package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }


    /**
     * 新增地址
     *
     * @param dto
     */
    @Override
    @Transactional( rollbackFor = Exception.class)
    public void add(AddressBookUpsertReqDTO dto) {
        //先进行健壮性检测
        if (dto == null) {
            throw new CommonException("请输入有效的地址");
        }
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        //设置经纬度
        String location = dto.getLocation();
        String[] split = location.split(",");
        addressBook.setLon(NumberUtils.parseDouble(split[0]));
        addressBook.setLat(NumberUtils.parseDouble(split[1]));
        Long userId = UserContext.currentUserId();
        addressBook.setUserId(userId);
        //查看是否设置默认地址
        if (dto.getIsDefault() == 1) {
            //设置默认地址 1.将之前所有的默认地址取消
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }

        boolean save = save(addressBook);
        if (!save) {
            throw new CommonException("新增地址失败");
        }
    }


    /**
     * 查询地址
     *
     * @param dto
     */
    @Override
    public PageResult<AddressBook> queryAddress(AddressBookPageQueryReqDTO dto) {
        if (dto.getPageNo() == null) {
            dto.setPageNo(1L);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(10L);
        }
        //获取当前的用户 id
        Long userId = UserContext.currentUserId();

//        //根据用户id分页查询地址
//        Page<AddressBook> page = new Page<>(dto.getPageNo(), dto.getPageSize());
//        Page<AddressBook> page1 = lambdaQuery()
//                .eq(AddressBook::getUserId, userId)
//                .page(page);
        PageResult<AddressBook> addressBookPageResult = PageHelperUtils.selectPage(dto, () -> getBaseMapper().queryAddress(userId));
        //构建结果
        return addressBookPageResult;
    }


    /**
     * 根据id回显地址
     *
     * @param id
     */
    @Override
    public AddressBook queryById(Long id) {
        Long userId = UserContext.currentUserId();
        if (id == null) {
            throw new CommonException("请选择地址");
        }
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted, 0)
                .one();
        if (addressBook == null) {
            throw new CommonException("查询失败");
        }
        return addressBook;
    }

    /**
     * 修改地址
     *
     * @param id
     * @param dto
     */
    @Transactional( rollbackFor = Exception.class)
    @Override
    public void updateAddress(Long id, AddressBookUpsertReqDTO dto) {
        if (id == null) {
            throw new CommonException("请选择地址");
        }
        // 获取当前用户id
        Long userId = UserContext.currentUserId();
        //删除旧地址
        boolean delete = this.removeById(id);
        if (!delete) {
            throw new CommonException("修改失败");
        }
        //添加新地址
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        addressBook.setId(Long.valueOf(id));
        //是否设置为默认
        if (dto.getIsDefault() == 1) {
            // 设置其他地址为非默认
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .eq(AddressBook::getIsDeleted, 0)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        boolean update = updateById(addressBook);
        if (!update) {
            throw new CommonException("修改失败");
        }
    }

    /**
     * 批量删除地址
     *
     * @param ids
     */
    @Transactional( rollbackFor = Exception.class)
    @Override
    public void deleteBatch(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new CommonException("请选择要删除的项");
        }
        //查看地址是否存在
        //拿到当前用户id
        Long userId = UserContext.currentUserId();
        Integer count = lambdaQuery().eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted, 0)
                .in(AddressBook::getId, ids)
                .count();
        if (count != ids.size()) {
            throw new CommonException("请选择正确的项");
        }
        boolean b = this.removeByIds(ids);
        if (!b) {
            throw new DBException("删除失败");
        }
    }

    /**
     * 设置/取消默认地址
     *
     * @param id
     * @param flag
     */
    @Transactional( rollbackFor = Exception.class)
    @Override
    public void setIsDefault(Long id, Integer flag) {
        if (id == null || flag == null) {
            throw new BadRequestException("请选择要设置的服务");
        }
        //查询地址是否存在
        AddressBook addressBook = this.getById(id);
        if (addressBook == null) {
            throw new ForbiddenOperationException("地址不存在，不能进行设置");
        }
        if (addressBook.getIsDefault() == flag) {
            throw new BadRequestException("该地址已经设为默认，请勿重复设置");
        }
        //获取当前 用户
        Long userId = UserContext.currentUserId();
        //如果是设置默认地址，则将当前用户的其他地址取消默认
        if (flag == 1) {
            boolean update = lambdaUpdate()
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .eq(AddressBook::getIsDeleted, 0)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
            System.out.println(  update);

        }
        //设置或取消默认
        boolean update = lambdaUpdate().eq(AddressBook::getId, id)
                .set(AddressBook::getIsDefault, flag)
                .eq(AddressBook::getUserId, userId)
                .update();
        if (!update) {
            throw new DBException("设置默认地址失败");
        }
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @Transactional( rollbackFor = Exception.class)
    @Override
    public AddressBook getDefaultAddress() {
        //获取当前用户
        Long userId = UserContext.currentUserId();
        AddressBook one = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted, 0)
                .eq(AddressBook::getIsDefault, 1)
                .one();
        if (one == null) {
            throw new BadRequestException("请先设置默认地址");
        }
        return one;
    }
}
